package com.comp7940.groupf.tgbot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.comp7940.groupf.tgbot.common.Constants;
import com.comp7940.groupf.tgbot.entity.User;
import com.comp7940.groupf.tgbot.exception.BizException;
import com.comp7940.groupf.tgbot.mapper.UserMapper;
import com.comp7940.groupf.tgbot.redis.RedisCache;
import com.comp7940.groupf.tgbot.service.UserService;
import com.comp7940.groupf.tgbot.util.CodeUtil;
import com.comp7940.groupf.tgbot.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper um;
    @Autowired
    EmailUtil  eu;
    @Autowired
    private RedisCache redisCache;
    @Override
    public Boolean suA(User user) {
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("tgacc", user.getTgacc());
        User u = um.selectOne(userWrapper);
        // 如果是 admin 直接授权码发邮箱
        if (!u.getRole().equals("admin")) {
            throw new BizException("Permission Denied");
        }
        String code = CodeUtil.generateVerificationCode();
        Map<String, Object> map = new HashMap<>();
        map.put("type", Constants.CODE_TYPE_AUTH);
        redisCache.setCacheMap(code, map);
        try {
            eu.sendSimpleEmail(u.getEmail(), "Please check your authentication verification code", Constants.STMP_BOT_NAME + " Your authentication verification code is " + code + ".");
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean check(Map<String, Object> args) {
        Map<String, Object> red = redisCache.getCacheMap((String) args.get("code"));
        if (red.get("type") == null) {
            return false;
        }
        if (red.get("type").equals(Constants.CODE_TYPE_AUTH)) {
            // 如果是鉴权 code
            redisCache.setCacheObject((String) args.get("tgacc"), true);
            // 用过一次就不能再用了
            redisCache.deleteObject((String) args.get("code"));
        }
        return true;
    }

    @Override
    public Boolean suE(User user) {
        Boolean is = true;
        try {
            is = redisCache.deleteObject(user.getTgacc());
        }
        catch (Exception e) {
            is = false;
        }
        return is;
    }
}
